
const arr1 = [
	{ id: 1, name: '部门1', pid: 0 },
	{ id: 2, name: '部门2', pid: 0 },
	{ id: 3, name: '部门3', pid: 1 },
	{ id: 4, name: '部门4', pid: 3 },
	{ id: 5, name: '部门5', pid: 4 }
];
const arr2 = [
	{ id: 1, name: '部门1', pid: 0 },
	{ id: 2, name: '部门2', pid: 0 },
	{ id: 3, name: '部门3', pid: 1 },
	{ id: 4, name: '部门4', pid: 3 },
	{ id: 5, name: '部门5', pid: 4 }
];
function getChildren1(arr, id) {
	const res = [];
	for (const item of arr) {
		if (item.pid === id) {
			// 找到当前id的子元素
			// 插入子元素，每个子元素的children通过回调生成
			res.push({ ...item, children: getChildren1(arr, item.id) });
		}
	}
	return res;
}

function getChildren2(arr) {
	const map = {}; // 生成map存储元素
	const result = []
	arr.forEach(item => {
		map[item.id] = Object.assign(item, {children: []})
	})
	arr.forEach(item => {
		let parent = map[item.pid]
		if (parent) {
			parent.children.push(item)
		} else {
			result.push(item)
		}
	})
	return result
}

console.log(getChildren1(arr1, 0));

console.log(getChildren2(arr2));

// ------------------------------------------------------------------------------------------

const obj = {
	id: 1,
	name: '部门1',
	pid: 0,
	children: [
		{
			id: 2,
			name: '部门2',
			pid: 1,
			children: []
		},
		{
			id: 3,
			name: '部门3',
			pid: 1,
			children: [
				{
					id: 4,
					name: '部门4',
					pid: 3,
					children: [
						{
							id: 5,
							name: '部门5',
							pid: 4,
							children: []
						}
					]
				}
			]
		}
	]
};

/**
 * @param {obj: object, res: array}
 * @return {arr: array}
 */
function fn2(obj, res = []) {
	// 默认初始结果数组为[]
	res.push(obj); // 当前元素入栈
	// 若元素包含children，则遍历children并递归调用使每一个子元素入栈
	if (obj.children && obj.children.length) {
		for (const item of obj.children) {
			fn2(item, res);
		}
	}
	return res;
}

console.log(fn2(obj));

function treeToArr(treeArr, res = []) {
	for (const itemTree of treeArr) {
		res.push(itemTree)
		if (itemTree.children && itemTree.children.length) {
			treeToArr(itemTree.children, res)
		}
	}
	return res
}

console.log(treeToArr([obj, obj]));